var stop_checking = false;

function examGrid()
{
    $('#examGrid').jqGrid({
                url: siteUrl + 'exam/get_exams',
                mtype: 'post',
                datatype: 'json',
                postData: {
                  group_id: $('#group_id').val()
                },
                colNames: ['ID','Exam name', 'Group', 'Exam' , 'Date Posted' , 'Status' , 'has_details', 'Operations'],
                colModel: [
                {name: 'exam_id', index: 'exam_id', hidden: true, key: true},
                {name: 'exam_name', index: 'exam_name'},
                {name: 'groups_group_id', index: 'groups_group_id', hidden: true},
                {name: 'exam_kind', index: 'exam_kind', hidden: false},
                {name: 'date_posted', index: 'date_posted', hidden: false},
                {name: 'status', index: 'status', hidden: false},
                {name: 'term', index: 'term', hidden: true},
                {name: 'ops', index: 'ops', align: 'center', sortable: false, formatter: examOperations}
                ],
            autowidth: true,
            height: '200',
            pager: $('#pagination'),
            sortname: 'exam_id',
            sortorder: 'asc',
            viewrecords: true,
            rownumbers: true
    });
}

function examOperations(cell, opts, rowObj)
{
    var id = opts.rowId;
    var group_id = rowObj[2];
    var status = rowObj[5];
    var has_term = rowObj[6];
    
    var add_question = '<a href="' + siteUrl + 'exam/add_details/' + group_id + '/' + id + '" title="Add Exam Details" class="icon icon-add"></a>';
    add_question = (user_type == 'student' || has_term != '') ? '<span class = "icon" ></span>' : add_question;

    var close = '<a onclick = "close_exam_dialog('+ id +')" href="javascript:void(0)" title="Close Exam" class="icon icon-delete"></a>';
    close = (user_type == 'student' || status == 'Closed' || status == 'Inactive') ? '<span class = "icon" ></span>' : close;

    var open = '<a onclick = "open_exam_dialog('+ id +')" href="javascript:void(0)" title="Open Exam" class="icon icon-success"></a>';
    open = (user_type == 'student' || status != 'Inactive' || has_term == '' ) ? '<span class = "icon" ></span>' : open;

    var take = '<a href="' + siteUrl + 'exam/take_exam/' + group_id + '/' + id + '" title="Take exam" class="icon24 icon-board"></a>';
    take = (user_type == 'instructor' || status != 'Active' ) ? '<span class = "icon24" ></span>' : take;
    
    return add_question + close + open +take;
}

function examRules()
{

  $.validator.addMethod("check_qty",function(value, element, params) {
        if (value == 1) {
            $.validator.messages.check_qty = 'Qty cannot have a value of  1.'
            return false;
        }

        return true

    }, '');

  $.validator.addMethod("less_five",function(value, element, params) {
        if (value < 5 && value != 0) {
            $.validator.messages.less_five = 'Cannot have a value less than 5 but can have a value of 0.'
            return false;
        }

        return true

    }, '');

    $('#exam_form').validate({
        debug: true,
        rules: {
           exam_name:{
                required: true
            }
           ,exam_kind:{
                required: true
            }
           ,identification_no_terms:{
                required: true
                ,number: true
            }
           ,multiple_no_terms:{
                required: true
                ,number: true
                ,less_five: true
            }
           ,match_no_terms:{
                required: true
                ,number: true
                ,check_qty: true
                ,max: 5
            }
           ,true_false_no_terms:{
                required: true
                ,number: true
            }
        },
        messages: {
            exam_name:  $.Msgs('required')
            ,exam_kind:  $.Msgs('required')
            ,identification_no_terms:{
                required: $.Msgs('required')
                ,number: $.Msgs('integer')
            }
            ,multiple_no_terms:{
                required: $.Msgs('required')
                ,number: $.Msgs('integer')
            }
            ,match_no_terms:{
                required: $.Msgs('required')
                ,number: $.Msgs('integer')
                ,max: $.Msgs('max','',5)
            }
            ,true_false_no_terms:{
                required: $.Msgs('required')
                ,number: $.Msgs('integer')
            }
        },
        onkeyup: false,
        focusInvalid: true,
        errorElement: 'span',
        errorPlacement: function(error, element) {
            $(element).next('.icon-error').remove();
            $(element).parent().append('<span class="icon icon-error"></span>');
            var icon = $(element).next('span');

            icon.qtip({
                content: $(error).text(),
                position: {
                    corner: {
                        target: 'rightTop',
                        tooltip: 'leftBottom'
                    }
                },
                hide: {
                    when: 'inactive',
                    delay: 1500
                },
                style: 'fielderror'
            });
        },
        highlight: function(element, errorClass) {
            $(element).parent().addClass('ui-state-error ui-corner-all');
        },
        unhighlight: function(element, errorClass) {
            $(element).next('.icon-error').remove();
            $(element).parent().removeClass('ui-state-error ui-corner-all');
        },
        submitHandler: function(form) {
            display_exam_warning(form);
        }
    });

}

function examDetailsRules()
{
    $('#exam_details_form').validate({
        debug: true,
        rules: {

        },
        messages: {

        },
        onkeyup: false,
        focusInvalid: true,
        errorElement: 'span',
        errorPlacement: function(error, element) {
            $(element).next('.icon-error').remove();
            $(element).parent().append('<span class="icon icon-error"></span>');
            var icon = $(element).next('span');

            icon.qtip({
                content: $(error).text(),
                position: {
                    corner: {
                        target: 'rightTop',
                        tooltip: 'leftBottom'
                    }
                },
                hide: {
                    when: 'inactive',
                    delay: 1500
                },
                style: 'fielderror'
            });
        },
        highlight: function(element, errorClass) {
            $(element).parent().addClass('ui-state-error ui-corner-all');
        },
        unhighlight: function(element, errorClass) {
            $(element).next('.icon-error').remove();
            $(element).parent().removeClass('ui-state-error ui-corner-all');
        },
        submitHandler: function(form) {
            saveExamDetail()
        }
    });

}

function display_exam_warning(form) {
   $('#ddialog').attr('title', 'Warning!');
   $('#ddialog').text('Once save it cannot be updated. Do you wish to continue?');
   $('#ddialog').dialog({
            resizable: false,
            height: '200',
            width: '300',
            modal: true,
            buttons: {
                    'No': function() {
                            $(this).dialog('close');
                    },
                    'Yes': function() {
                        form.submit();
                    }
            },
            close: function() {
                    $(this).dialog('destroy');

            }
    }).removeClass('hidden');
}
function close_exam_dialog(id) {
   $('#ddialog').attr('title', 'Closing Exam');
   $('#ddialog').text('Closing exam can cause exam/activity takers to lose some scores. Do you wish to continue?');
   $('#ddialog').dialog({
            resizable: false,
            height: 'auto',
            width: '300',
            modal: true,
            buttons: {
                    'No': function() {
                            $(this).dialog('close');
                    },
                    'Yes': function() {
                        close_exam(id);
                    }
            },
            close: function() {
                    $(this).dialog('destroy');

            }
    }).removeClass('hidden');
}
function open_exam_dialog(id) {
   $('#ddialog').attr('title', 'Opening Exam');
   $('#ddialog').text('Do you wish to continue?');
   $('#ddialog').dialog({
            resizable: false,
            height: 'auto',
            width: '300',
            modal: true,
            buttons: {
                    'No': function() {
                            $(this).dialog('close');
                    },
                    'Yes': function() {
                        open_exam(id);
                    }
            },
            close: function() {
                    $(this).dialog('destroy');

            }
    }).removeClass('hidden');
}

function open_exam(id){
    $.loading('Opening Exam');

    $.ajax({
        url: siteUrl + 'exam/open_exam',
        type: 'post',
        data: {
            exam_id: id
        },
        success: function(response) {
            if (response)
            {
                window.location = siteUrl + 'exam/list_records/' + $('#group_id').val();
            }
        }
    });
}
function close_exam(id){
    $.loading('Closing Exam');

    $.ajax({
        url: siteUrl + 'exam/close_exam',
        type: 'post',
        data: {
            exam_id: id
        },
        success: function(response) {
            if (response)
            {
                window.location = siteUrl + 'exam/list_records/' + $('#group_id').val();
            }
        }
    });
}


function saveExamDetail(){
    $.loading('Exam Saving - Step 2');
    
    $.ajax({
        url: siteUrl + 'exam/submit_details',
        type: 'post',
        data: $('#exam_details_form').serialize(),
        success: function(response) {
            if (response)
            {
                window.location = siteUrl + 'exam/list_records/' + $('#group_id').val();
            }
        }
    });
}



function take_exam_dialog() {
   stop_checking = true;

   $('#ddialog').attr('title', 'Warning!');
   $('#ddialog').text('Your about to submit this form. Do you wish to continue?');
   $('#ddialog').dialog({
            resizable: false,
            height: 'auto',
            width: '300',
            modal: true,
            buttons: {
                    'No': function() {
                        $(this).dialog('close');
                    },
                    'Yes': function() {
                        check_answer(true, true);
                        $(this).dialog('destroy');
                    }
            },
            close: function() {
                stop_checking = false;
                check_answer(false, false); //re-initialize checking
                $(this).dialog('destroy');
            }
    }).removeClass('hidden');
}

function check_answer(is_take_exam_save, is_force_save) {

    if (is_take_exam_save == true) {
        check_written();
        check_multiple();
        check_match();
        check_true_false();
    }
    
    save_score(is_take_exam_save, is_force_save);
}

function save_score(is_take_exam_save, is_force_save) {
    if (is_take_exam_save == true) {
        var identificaiton_ids_arr = [];
        var mutiple_ids_arr = [];
        var match_ids_arr = [];
        var truefalse_ids_arr = [];

        var wrong_total = $('.wrong-q').length;
        var right_total = $('.right-q').length;
        var over_all = parseInt(wrong_total) + parseInt(right_total);

        $('#score').removeClass('hidden');
        $('#actual_score').text(right_total);
        $('#actual_score_h').val(right_total);
        $('#total_score').text(over_all);
        $('#total_score_h').val(over_all);

        $('input[id^="written_"]').each(function(e) {
            var unique_id = $(this).attr('id');
            unique_id = unique_id.substr(8);
            identificaiton_ids_arr.push(unique_id);
        });
        $('input[id^="multiple_"]').each(function(e) {
            var unique_id = $(this).attr('id');
            unique_id = unique_id.substr(9);
            mutiple_ids_arr.push(unique_id);
        });
        $('input[id^="match_"]').each(function(e) {
            var unique_id = $(this).attr('id');
            unique_id = unique_id.substr(6);
            match_ids_arr.push(unique_id);
        });
        $('input[id^="tf_"]').each(function(e) {
            var unique_id = $(this).attr('id');
            unique_id = unique_id.substr(3);
            truefalse_ids_arr.push(unique_id);
        });

        $('#identification_ids').val(identificaiton_ids_arr.join('|'))
        $('#mutiples_ids').val(mutiple_ids_arr.join('|'))
        $('#matching_ids').val(match_ids_arr.join('|'))
        $('#truefalse_ids').val(truefalse_ids_arr.join('|'))

        //remove submit button
        $('#save').remove();
        //display print button
        $('#print').removeClass('hidden');

        $.ajax({
            url: siteUrl + 'exam/save_score',
            type: 'POST',
            data: $('#exam_form').serialize(),
            dataType: 'json',
            success: function(response) {
                return true;
            }
        });

    }

    //end checking if exam is close if is_force_save = true
    if (is_force_save == false) {
        is_exam_close()
    }
    
}

function is_exam_close() {
    if (!stop_checking){
        $.ajax({
            url: siteUrl + 'exam/is_exam_close',
            type: 'POST',
            data: {
                exam_id: $('#exam_id').val()
            },
            dataType: 'json',
            success: function(response) {

                if (response == true) {
                    is_force_save = true;
                    is_take_exam_save = true;
                    is_force_save_dialog();
                }
                else {
                    is_force_save = false
                    is_take_exam_save = false
                }

                setTimeout("check_answer(is_take_exam_save, is_force_save)",2000);
            }
        });
    }
}

function is_force_save_dialog() {
   $('#ddialog').attr('title', 'Attention!');
   $('#ddialog').text('Your instructor has close the exam. Your answer has been submitted.');
   $('#ddialog').dialog({
            resizable: false,
            height: 'auto',
            width: '300',
            modal: true,
            buttons: {
                    'Ok': function() {
                        $(this).dialog('close');
                    }
            },
            close: function() {
                    $(this).dialog('destroy');

            }
    }).removeClass('hidden');
}

function check_written(){
    $('input[id^="written_"]').each(function(e) {
        var the_line = $(this).closest('.line');
        var the_question = $(the_line).find('label > span').text();
        var the_field = $(this).closest('.field');
        var correct_answer = $(this).attr('ans');
        var unique_id = $(this).attr('id');
        unique_id = unique_id.substr(8);
        var answer = $(this).val();

        if (answer.toUpperCase() == correct_answer.toUpperCase()) {
            $(the_line).addClass('right-q');
            code = '<p><span class="correct">CORRECT:</span> <span >'+correct_answer+'</span></p>';

            code += '<input type= "hidden" id = "written_'+ unique_id +'" name = "written_'+ unique_id +'"  value = "'+ answer +'|correct"/ >';
        }
        else {
            $(the_line).addClass('wrong-q');
            if ($(this).val() == '') {
                answer = 'No answer';
            }
            else {
                answer = $(this).val();
            }

            code = '<p><span class="incorrect">INCORRECT:</span> You gave <span class="incorrect">'+ answer +'</span></p>'
            code += '<p><span class="correct">ANSWER:</span> <span>'+correct_answer+'</span></p>';

            code += '<input type= "hidden" id = "written_'+ unique_id +'" name = "written_'+ unique_id +'"  value = "'+ answer +'|wrong"/ >';
        }

        code += '<input type= "hidden" id = "writtenq_'+ unique_id +'" name = "writtenq_'+ unique_id +'"  value = "'+ the_question +'"/ >';
        $(the_field).append(code);
        $(this).remove();
    })
}
function check_multiple(){
    $('input[id^="multiple_"]').closest('ul').each(function(e) {
        var ul = this;
        var no_answer = false;

        //get correct answer
        $(this).find('input[id^="multiple_"]').each(function(e){
            if ($(this).val() == '1') {
                correct_answer = $(this).next('span').text();
                return false;
            }
        });
        //check if no answer
        $(this).find('input[id^="multiple_"]').each(function(e){
            if ($(this).is(':checked') == false) {
                no_answer = true;
            }
            else {
                no_answer = false;
                return false;
            }
        });

        $(this).find('input[id^="multiple_"]').each(function(e){
            var the_line = $(this).closest('.line');
            var the_question = $(the_line).find('label > span').text();
            var the_field = $(this).closest('.field');
            var unique_id = $(this).attr('id');
            unique_id = unique_id.substr(9);
            var answer = $(this).val();
            var answer_given = $(this).next('span').text();


            if ($(this).is(':checked') == true && answer == '1') {
                
                $(the_line).addClass('right-q');
                code = '<p><span class="correct">CORRECT:</span> <span >'+correct_answer+'</span></p>';

                code += '<input type= "hidden" id = "multiple_'+ unique_id +'" name = "multiple_'+ unique_id +'"  value = "'+ answer_given +'|correct"/ >';
                code += '<input type= "hidden" id = "multipleq_'+ unique_id +'" name = "multipleq_'+ unique_id +'"  value = "'+ the_question +'"/ >';
                $(the_field).append(code);
                return false;
            }
            else if ($(this).is(':checked') == true && answer == '0' ){
                $(the_line).addClass('wrong-q');

                code = '<p><span class="incorrect">INCORRECT:</span> You gave <span class="incorrect">'+ answer_given +'</span></p>'
                code += '<p><span class="correct">ANSWER:</span> <span>'+correct_answer+'</span></p>';

                code += '<input type= "hidden" id = "multiple_'+ unique_id +'" name = "multiple_'+ unique_id +'"  value = "'+ answer_given +'|wrong"/ >';
                code += '<input type= "hidden" id = "multipleq_'+ unique_id +'" name = "multipleq_'+ unique_id +'"  value = "'+ the_question +'"/ >';
                $(the_field).append(code);
                return false;
            }
            else if (no_answer == true && $(this).is(':checked') == false ){
                $(the_line).addClass('wrong-q');
                code = '<p><span class="incorrect">INCORRECT:</span> You gave <span class="incorrect">No answer</span></p>'
                code += '<p><span class="correct">ANSWER:</span> <span>'+correct_answer+'</span></p>';

                code += '<input type= "hidden" id = "multiple_'+ unique_id +'" name = "multiple_'+ unique_id +'"  value = "No answer|wrong"/ >';
                code += '<input type= "hidden" id = "multipleq_'+ unique_id +'" name = "multipleq_'+ unique_id +'"  value = "'+ the_question +'"/ >';
                $(the_field).append(code);
                return false;
            }
            
        })

        $(ul).remove(); //remove radio buttons
    })
}

function check_match(){
    $('input[id^="match_"]').each(function(e) {
        var the_line = $(this).closest('.line');
        var the_question = $(the_line).find('label > span').text();
        var the_field = $(this).closest('.field');
        var match_key = $(this).attr('match');
        var match_key_label = match_key + ':';
        var unique_id = $(this).attr('id');
        unique_id = unique_id.substr(6);
        var answer_input = $(this).val(); //not changing
        var answer = $(this).val(); //changing
        var answer_quote = answer+':';//not changing
        var correct_answer;
        var correct_answer_label;
        var answer_label;

        //match correct answer
        $('#match-right1').find('label').each(function(e){
            correct_answer = $(this).text();
            correct_answer_label = $(this).next().text();
            if (match_key_label.toUpperCase() == correct_answer.toUpperCase()) {
                return false;
            }
        });

        
        if (answer_quote.toUpperCase() == match_key_label.toUpperCase()) {
            $(the_line).addClass('right-q');
            code = '<p><span class="correct">CORRECT:</span> <span >'+correct_answer_label+'</span></p>';
            code += '<input type= "hidden" id = "match_'+ unique_id +'" name = "match_'+ unique_id +'"  value = "'+ correct_answer_label +'|correct"/ >';
        }
        else {
            //for wrong answer
            $('#match-right1').find('label').each(function(e){
                match_right_label = $(this).text();
                answer_label = $(this).next().text();

                if (match_right_label.toUpperCase() == answer_quote.toUpperCase()) {
                    answer = '\''+ answer_input + '\': ' +answer_label;
                    return false;
                }
                else {
                    answer = '\''+ answer_input + '\': No matching answer found.';
                }
            });

            $(the_line).addClass('wrong-q');
            if (answer_input == '') {
                answer = 'No answer';
            }

            code = '<p><span class="incorrect">INCORRECT:</span> You gave <span class="incorrect">'+ answer +'</span></p>'
            code += '<p><span class="correct">ANSWER:</span> <span>'+correct_answer_label+'</span></p>';

            code += '<input type= "hidden" id = "match_'+ unique_id +'" name = "match_'+ unique_id +'"  value = "'+ answer +'|wrong"/ >';
        }

        code += '<input type= "hidden" id = "matchq_'+ unique_id +'" name = "matchq_'+ unique_id +'"  value = "'+ the_question +'"/ >';

        $(the_field).append(code);
        $(this).remove();
    })
}

function check_true_false() {
    $('input[id^="tf_"]').closest('div').each(function(e) {
        var div = this;
        var no_answer = false;

        //get correct answer
        $(this).find('input[id^="tf_"]').each(function(e){
            if ($(this).val() == '1') {
                correct_answer = $(this).next('span').text();
                return false;
            }
        });
        //check if no answer
        $(this).find('input[id^="tf_"]').each(function(e){
            if ($(this).is(':checked') == false) {
                no_answer = true;
            }
            else {
                no_answer = false;
                return false;
            }
        });

        $(this).find('input[id^="tf_"]').each(function(e) {
            var the_line = $(this).closest('.line');
            var the_question = $(the_line).find('label > span').text();
            var the_field = $(this).closest('.field');
            var unique_id = $(this).attr('id');
            unique_id = unique_id.substr(3);
            var answer = $(this).val();
            var answer_given = $(this).next('span').text();

            if ($(this).is(':checked') == true && answer == '1') {
                $(the_line).addClass('right-q');
                code = '<p><span class="correct">CORRECT:</span> <span >'+answer_given+'</span></p>';

                code += '<input type= "hidden" id = "tf_'+ unique_id +'" name = "tf_'+ unique_id +'"  value = "'+ answer_given +'|correct"/ >';
                code += '<input type= "hidden" id = "tfq_'+ unique_id +'" name = "tfq_'+ unique_id +'"  value = "'+ the_question +'"/ >';
                $(the_field).append(code);
                return false;
            } else if ($(this).is(':checked') == true && answer == '0' ){
                $(the_line).addClass('wrong-q');

                code = '<p><span class="incorrect">INCORRECT:</span> You gave <span class="incorrect">'+ answer_given +'</span></p>'
                code += '<p><span class="correct">ANSWER:</span> <span>'+correct_answer+'</span></p>';

                code += '<input type= "hidden" id = "tf_'+ unique_id +'" name = "tf_'+ unique_id +'"  value = "'+ answer_given +'|wrong"/ >';
                code += '<input type= "hidden" id = "tfq_'+ unique_id +'" name = "tfq_'+ unique_id +'"  value = "'+ the_question +'"/ >';

                $(the_field).append(code);
                return false;
            }
            else if (no_answer == true && $(this).is(':checked') == false ){
                $(the_line).addClass('wrong-q');
                code = '<p><span class="incorrect">INCORRECT:</span> You gave <span class="incorrect">No answer</span></p>'
                code += '<p><span class="correct">ANSWER:</span> <span>'+correct_answer+'</span></p>';

                code += '<input type= "hidden" id = "tf_'+ unique_id +'" name = "tf_'+ unique_id +'"  value = "No answer|wrong"/ >';
                code += '<input type= "hidden" id = "tfq_'+ unique_id +'" name = "tfq_'+ unique_id +'"  value = "'+ the_question +'"/ >';
                $(the_field).append(code);
                return false;
            }

        });

        $(div).remove(); //remove radio buttons
    });
}
//var before_answer;
//
//function get_answer(element) {
//    before_answer = $(element).val();
//    before_answer = before_answer + ':';
////    console.debug(before_answer);
////    console.debug('focysing');
//}
//
//function linethrough(element) {
//    var answer = $(element).val();
//    answer = $(element).val() +':';
//
//
//    $('#match-right1').find('label').each(function(e){
//        right_answer = $(this).text();
//
//        if (answer.toUpperCase() == right_answer.toUpperCase()) {
//            $(this).next().addClass('line-through');
//            return false;
//        }
//        else {
//             $(this).next().removeClass('line-through');
//            //return false;
//        }
//
////       console.debug(answer.toUpperCase());
////       console.debug(right_answer.toUpperCase());
////       console.debug('1');
////       console.debug(before_answer.toUpperCase());
////       console.debug(right_answer.toUpperCase());
////       console.debug('2');
//
////        if (answer.toUpperCase() != right_answer.toUpperCase() && before_answer.toUpperCase() == right_answer.toUpperCase()) {
////            $(this).next().removeClass('line-through');
////            return false;
////        }
//    });
//}

function deleteLesson(id)
{
    $.loading('Lesson - Deleting Record');

    $.ajax({
        url: siteUrl + 'lesson/delete/' + id,
        type: 'post',
        dataType: 'json',
        success: function(response) {
            if (response == true)
            {
                window.location = siteUrl + 'lesson/list_records/' + $('#group_id').val();
            }

        }
    });
}



function filterExamGroup(){

    $('#examGrid').setGridParam({
    postData:
        {
            search: $('#search').val(),
            date_posted: $('#date_posted').val()
        }
    }).trigger('reloadGrid');
}